import webapp2
import logging
import random
from google.appengine.ext import ndb


class Sound(ndb.Model):
    data = ndb.BlobProperty()


class SoundUploadHandler(webapp2.RequestHandler):
    def get(self):
        self.__render_form()

    def post(self):

        file = self.request.get('file')
        if file:
            logging.info('Uploading sound file')
            sound = Sound()
            sound.data = file.encode('base64')
            sound.put()

            response = {'id': sound.key.id()}
            self.response.out.write(response)
        else:
            logging.info("Sound file wasn't found")
            self.__render_form();

    def __render_form(self):
        self.response.out.write(
            '<html>'
            '   <head>'
            '       <title>API Tester</title>'
            '   </head>'
            '   <body>'
            '       <form method="post" enctype="multipart/form-data">'
            '       File: <input type="file" name="file">'
            '       <input type="submit" value="Submit">'
            '       </form>'
            '   </body>'
            '</html>')


class RandomSoundHandler(webapp2.RequestHandler):
    def get(self):
        sound_keys = []
        for sound_key in Sound.query().iter(keys_only=True):
            sound_keys.append(sound_key)

        sound_key = sound_keys[random.randint(0, len(sound_keys)-1)]

        response = {'sound': {
            'id': sound_key.id(),
            'data': sound_key.get().data
        }}
        self.response.out.write(response)


app = webapp2.WSGIApplication([
    ('/sound/upload', SoundUploadHandler),
    ('/sound/random', RandomSoundHandler)
], debug=True)